import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/stores/userStore'

const routes = [
  {
    path: '/', // 重定向到首页
    redirect: '/index'
  },
  {
    path: '/index', // 首页
    name: 'index',
    component: () => import('../views/index/index.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/my', // 我的
    name: 'my',
    component: () => import('../views/my/index.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/record', // 记录
    name: 'record',
    component: () => import('../views/record/index.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/notice', // 公告
    name: 'notice',
    component: () => import('../views/notice/index.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/status', // 当前
    name: 'status',
    component: () => import('../views/status/index.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/login', // 登录
    name: 'login',
    component: () => import('../views/my/login.vue')
  },
  {
    path: '/register', // 注册
    name: 'register',
    component: () => import('../views/my/register.vue')
  },
  {
    path: '/404', // 找不到
    name: 'NotFound',
    component: () => import('../views/other/404.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to) => {
  // ✅ 这将起作用，因为路由器在之后开始导航
  // 路由已安装，pinia 也将安装
  const userStore = useUserStore()
  if (to.meta.requiresAuth && !userStore.isLogged) return '/login'
})

export default router